package com.fetech.melon.idfactory.config;

import com.fetech.melon.context.property.DefaultConfigLoader;
import com.fetech.melon.context.property.MelonPropertyPlaceholderConfigurer;
import com.fetech.melon.idfactory.impl.CachedUidGenerator;
import com.fetech.melon.idfactory.worker.DisposableWorkerIdAssigner;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

/**
 * Created by ZhangGang on 2017/10/25.
 */
@Configuration
public class CachedUidConfig {
    private static final String configPath = "META-INF/melon/idfactory_default_conf.properties";

    @Resource
    private ApplicationContext context;

    @Resource
    @SuppressWarnings("SpringJavaAutowiringInspection")
    private MelonPropertyPlaceholderConfigurer propertyTemplate;

    @PostConstruct
    public void init() {
        DefaultConfigLoader.getInstance().load(configPath);
    }

    @Bean(name = "disposableWorkerIdAssigner")
    public DisposableWorkerIdAssigner disposableWorkerIdAssigner() {
        return new DisposableWorkerIdAssigner();
    }

    @Bean(name = "cachedUidGenerator")
    public CachedUidGenerator cachedUidGenerator() {
        CachedUidGenerator cachedUidGenerator = new CachedUidGenerator();
        cachedUidGenerator.setWorkerIdAssigner(context.getBean("disposableWorkerIdAssigner", DisposableWorkerIdAssigner.class));
        cachedUidGenerator.setBoostPower(propertyTemplate.getInt("uid.boostPower", DefaultConfigLoader.getInstance().getInt("uid.default.boostPower")));
        cachedUidGenerator.setPaddingFactor(propertyTemplate.getInt("uid.paddingFactor", DefaultConfigLoader.getInstance().getInt("uid.default.paddingFactor")));
        cachedUidGenerator.setScheduleInterval(propertyTemplate.getInt("uid.scheduleInterval", DefaultConfigLoader.getInstance().getInt("uid.default.scheduleInterval")));
        cachedUidGenerator.setTimeBits(propertyTemplate.getInt("uid.timeBits", DefaultConfigLoader.getInstance().getInt("uid.default.timeBits")));
        cachedUidGenerator.setWorkerBits(propertyTemplate.getInt("uid.workerBits", DefaultConfigLoader.getInstance().getInt("uid.default.workerBits")));
        cachedUidGenerator.setSeqBits(propertyTemplate.getInt("uid.seqBits", DefaultConfigLoader.getInstance().getInt("uid.default.seqBits")));
        cachedUidGenerator.setEpochStr(propertyTemplate.getString("uid.epochStr", DefaultConfigLoader.getInstance().getString("uid.default.epochStr")));
        return cachedUidGenerator;
    }

}
